﻿// Add Usings:
using Lsk.Business;
using Lsk.Business.DTO;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web.Http;

namespace lsk.Web.Security
{
    public class ApplicationOAuthServerProvider
      : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(
            OAuthValidateClientAuthenticationContext context)
        {
            // This call is required...
            // but we're not using client authentication, so validate and move on...
            await Task.FromResult(context.Validated());
        }

        
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            string userName = context.UserName;
            string password = context.Password;

            if (password.Trim() == "")
            {
                // check FB login first
                Users user = new Users();
                LoginResponse output = user.isFbUser(userName);

                // if (context.Password != "password")
                if (output.isUser == "0")
                {
                    context.SetError(
                        "invalid_grant", "The facebook user account is not registered in this portal yet. Please register first.");
                    context.Rejected();
                    return;
                }

                // Create or retrieve a ClaimsIdentity to represent the 
                // Authenticated user:
                ClaimsIdentity identity =
                    new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("user_name", context.UserName));

                var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    {
                        "UserType", output.UserType
                    },

                });

                var ticket = new AuthenticationTicket(identity, props);

                // Identity info will ultimately be encoded into an Access Token
                // as a result of this call:
                context.Validated(ticket);
            }
            else
            {


                Users user = new Users();
                LoginResponse output = user.isUser(userName, password);

                // if (context.Password != "password")
                if (output.isUser == "0")
                {
                    context.SetError(
                        "invalid_grant", "The user name or password is incorrect.");
                    context.Rejected();
                    return;
                }

                // Create or retrieve a ClaimsIdentity to represent the 
                // Authenticated user:
                ClaimsIdentity identity =
                    new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("user_name", context.UserName));

                var props = new AuthenticationProperties(new Dictionary<string, string>
            {
                {
                    "UserType", output.UserType
                },

            });

                var ticket = new AuthenticationTicket(identity, props);

                // Identity info will ultimately be encoded into an Access Token
                // as a result of this call:
                context.Validated(ticket);
            }
        }

        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
            {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }
            return Task.FromResult<object>(null);
        }

        public static AuthenticationProperties CreateProperties(string userName, string Roles)
        {
            IDictionary<string, string> data = new Dictionary<string, string>
        {
            { "userName", userName },
            {"roles",Roles}
        };
            return new AuthenticationProperties(data);
        }
    }
}